alert("recommender.js loaded");

function Recommender() {
	this.profileManager = new ProfileManager;
	this.serverURL = 'http://localhost:8888/recommender/list';
	this.clientId = networkObject.GetMAC();
	this.previousChannel = windowObject.GetCurrentChannel_Name();
	this.previousProgram = tvObject.GetPresentProgram_Title();
	this.now = timeObject.GetEpochTime();
	this.recommendations = null;
	this.appConfig = this.profileManager.loadAppConfig();
	this.schedules = new Array();
}

Recommender.prototype.sendRequests = function() {
	var XHRObject = new XMLHttpRequest();

	if (XHRObject) {
		XHRObject.open("POST", this.serverURL, false);
		XHRObject.setRequestHeader("Accept-Charset", "UTF-8");
		//var profile = this.buildProfile();
		var profile  = '<client-profile id="Client 1"><available-programs><program title="Telecursos"/><program title="Adnet ao vivo"/><program title="Aconteceu"/><program title="Aqui na Clube"/><program title="PE Dá Sorte"/></available-programs><current-program title="Quinta Categoria" channel="MTV"/><preferred-programs><program title="A grande família" channel="Globo" rating="0.8"/><program title="Andy M. Show" channel="MTV" rating="0.57"/><program title="A Tarde é Sua" channel="RedeTV!" rating="0.75"/></preferred-programs>';
		profile += '<black-list><program title="Clipes Comédia"/></black-list>';
		profile += '<app-config><length>' + this.appConfig['length'] + '</length><display-time>Ao Final do Programa</display-time><interval>Agora</interval></app-config>';
		profile += '</client-profile>';
		//alert(profile);
		//XHRObject.send(profile);
		//this.recommendations = XHRObject.responseText;
		//alert(XHRObject.responseText);
		this.recommendations  = '$Séries/seriado;Lara com Z;Globo;Dr. House;SBT;Prison Break;Globo;';
        this.recommendations += '$Informação;PC na TV;MTV;Globo Mar;Globo;Sagrado;Globo;';
        this.recommendations += '$Educativo;Telecursos;Globo;Adnet ao vivo;MTV;';
        this.recommendations += '$Debate/entrevista;Programa do Jô;Globo;';
        this.recommendations += '$Notícias;Jornal da Globo;Globo;Jornal do SBT Noite;SBT';
		XHRObject.destroy();
	}
}

Recommender.prototype.getRecommendations = function() {
	if (this.recommendations.length <= 2)
		return new Array();
	
	var formattedResponse = new Array();
	var genres = new Array();
	var programs = new Array();
	var response = this.recommendations.split(";");
	var epgSize = tvObject.GetProgramList_Size();
	var epg = new Array();
	
	alert(epgSize);
	for (var i = 0; i < epgSize; i++)
		epg[tvObject.GetProgram_Title(i)] = timeObject.ConvertEpochToLocalTime(tvObject.GetProgram_StartTime(i));
        
    epg['Lara com Z'] = '23:15';
    epg['Dr. House'] = '23:30';
    epg['Prison Break'] = '02:30';

    epg['Jornal da Globo'] = '00:25';
    epg['Jornal do SBT Noite'] = '00:30';

    epg['PC na TV'] = '23:30';
    epg['Globo Mar'] = '00:05';
    epg['Sagrado'] = '04:57';

    epg['Programa do Jô'] = '00:55';
	
	for (var i = 0, j = 0; i < response.length;) {
		if (response[i].indexOf("$") != -1) {
			genres[j] = response[i].substr(1);
			programs[j++] = new Array();
			i++;
			continue;
		}
		programs[j-1].push(response[i] + " - " + response[i+1] + " (" + epg[response[i]] + ")");
		i += 2;
	}
	
	return { genres: genres, programs: programs };
}

Recommender.prototype.buildProfile = function () {
	var profileElement = '<client-profile id="' + this.clientId + '">';
	
	var epgProgramListElement = this.buildProgramList();
	
	var currentProgramElement = '<current-program title="' + tvObject.GetPresentProgram_Title() + '" channel="' + windowObject.GetCurrentChannel_Name() + '"/>';

	var preferredPrograms = this.profileManager.getPreferredPrograms();
	var preferredProgramsElement = '<preferred-programs>';
	for (i in preferredPrograms)
		preferredProgramsElement += '<program title="' + preferredPrograms[i].program + '" channel="' + preferredPrograms[i].channel + '" doi="' + preferredPrograms[i].doi + '"/>';
	preferredProgramsElement += '</preferred-programs>';

	var blackList = this.profileManager.getBlackList();
	var blackListElement = '<black-list>';
	for (i in blackList) {
		if (blackList[i].type == 'p')
			blackListElement += '<program title="' + blackList[i].value + '"/>';
		else if (blackList[i].type == 'g')
			blackListElement += '<genre name="' + blackList[i].value + '"/>';
	}
	blackListElement += '</black-list>';

	var appConfig = this.profileManager.loadAppConfig();
	var appConfigElement = '<app-config>';
	appConfigElement += '<length>' + appConfig['length'] + '</length>';
	appConfigElement += '<display-time>' + appConfig['display-time'] + '</display-time>';
	appConfigElement += '<interval>' + appConfig['interval'] + '</interval>';
	appConfigElement += '</app-config>';

	profileElement += epgProgramListElement + currentProgramElement;
	profileElement += preferredProgramsElement + blackListElement;
	profileElement += appConfigElement;
	profileElement += '</client-profile>';

	return profileElement;
}

Recommender.prototype.buildProgramList = function () {
	var availableProgramsElement = '<available-programs>';
	var programList = this.getEPG();
	var filterPrograms = true;

	for (i in programList)
		if (filterPrograms && timeObject.GetEpochTime() <= tvObject.GetProgram_StartTime(i))
			availableProgramsElement += '<program title="' + programList[i] + '"/>';
	availableProgramsElement += '</available-programs>';

	return availableProgramsElement;
}

Recommender.prototype.getEPG = function () {
	if (parseInt(this.appConfig['interval']) == 0) //Agora
		tvObject.GetProgramList(timeObject.GetEpochTime(), 0);
	else if (parseInt(this.appConfig['interval']) == 1) //Resto do Dia
		tvObject.GetProgramList(timeObject.GetEpochTime(), 3600*24 - timeObject.GetEpochTime());
	var programList = new Array();
	var programListSize = tvObject.GetProgramList_Size();

	for (var i = 0; i < programListSize; i++)
		programList[i] = tvObject.GetProgram_Title(i);

	return programList;
}

Recommender.prototype.addToBlackList = function(type, item) {
	this.profileManager.addToBlackList(type, item);
}

Recommender.prototype.existsInBlackList = function(type, item) {
	return this.profileManager.existsInBlackList(type, item);
}

Recommender.prototype.removeFromBlackList = function(item) {
	this.profileManager.removeFromBlackList(item);
}

Recommender.prototype.existsPreferredProgram = function(program) {
	return this.profileManager.existsPreferredProgram(program);
}

Recommender.prototype.channelChanged = function() {
	var average = ((timeObject.GetEpochTime() - this.now) / tvObject.GetPresentProgram_Duration()).toFixed(2);

	if (average >= 0.01) {
		if (this.profileManager.existsPreferredProgram(this.previousProgram, this.previousChannel))
			this.profileManager.updatePreferredProgram(this.previousProgram, this.previousChannel, average);
		else
			this.profileManager.addPreferredProgram(this.previousProgram, this.previousChannel);
	}
	this.now = timeObject.GetEpochTime();
	this.previousChannel = windowObject.GetCurrentChannel_Name();
	this.previousProgram = tvObject.GetPresentProgram_Title();
}

Recommender.prototype.canSchedule = function(item) {
	var epgSize = tvObject.GetProgramList_Size();
	var programTitle = item.split(" - ")[0];
	
	for (var i = 0; i < epgSize; i++) {
		if (programTitle == tvObject.GetProgram_Title(i) &&
			timeObject.GetEpochTime() < tvObject.GetProgram_StartTime(i)) {
				this.schedules.push(programTitle);
				return true;
			}
	}
	
	//return false;
    return true;
}

Recommender.prototype.getScheduledProgram = function(item) {
	var epgSize = tvObject.GetProgramList_Size();
	var programTitle = item.split(" - ")[0];
	
	for (var i = 0; i < this.schedules.length; i++) {
		if (this.schedules[i] == programTitle) {
			var channelName = item.split(" - ")[1].split(" (")[0];
			var startTime;
		
			for (var i = 0; i < epgSize; i++)
				if (programTitle == tvObject.GetProgram_Title(i)) {
					startTime = tvObject.GetProgram_StartTime(i);
					break;
				}
		
			return { program: programTitle, channel: channelName, startTime: startTime - timeObject.GetEpochTime() - 300 };
		}
	}
	
	return undefined;
}
